package com.example.tumasstest;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Arrays;

public class UDPManager {
    private static final int READ_PORT = 12344;
    private static final int WRITE_PORT = 12345;

    private DatagramSocket socket;
    private Handler handler;

    public interface DataCallback {
        void onDataReceived(byte[] data);
    }

    public interface SendResult {
        void onSendResult(boolean result);
    }

    public UDPManager() {
        handler = new Handler(Looper.getMainLooper());
    }

    public void startReading(final DataCallback callback) {
        new Thread(new Runnable() {
            byte[] last = new byte[1024];
            @Override
            public void run() {
                try {
                    socket = new DatagramSocket(READ_PORT);
                    byte[] buffer = new byte[1024];
                    Arrays.fill(buffer, (byte) 0);
                    DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

                    while (true) {
                        socket.receive(packet);
                        final byte[] data = packet.getData();
                        boolean isEqual = Arrays.equals(data, last);
                        Log.d("0000000", "run: " + isEqual);
                        System.arraycopy(data, 0, last, 0, 1024);
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                callback.onDataReceived(data);
                            }
                        });
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public void stopReading() {
        if (socket != null) {
            socket.close();
        }
    }

    public void writeData(final byte[] data, SendResult result) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    InetAddress address = InetAddress.getByName("10.0.2.2");
                    DatagramPacket packet = new DatagramPacket(data, data.length, address, WRITE_PORT);
                    DatagramSocket writeSocket = new DatagramSocket();
                    writeSocket.send(packet);
                    writeSocket.close();
                    if (result != null) {
                        result.onSendResult(true);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    if (result != null) {
                        result.onSendResult(false);
                    }
                }
            }
        }).start();
    }
}
